import { ref } from 'vue';

export default function useFileUpload(props, proxy,getList) {
  const excelopen = ref(false);
  const uploadRef = ref({});

  // 上传成功回调
  const handleUploadSuccess = (res, file) => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("上传成功");
      excelopen.value = false;
      getList()
    } else {
      proxy.$modal.msgError(res.msg);
    }
    // 清理上次信息
    uploadRef.value.clearFiles();
    proxy.$modal.closeLoading();
  };

  // 上传失败
  const handleUploadError = () => {
    proxy.$modal.msgError("上传图片失败");
    proxy.$modal.closeLoading();
  };

  // 上传前loading加载
  const handleBeforeUpload = (file) => {
    let isImg = false;
    if (props.fileType.length) {
      const fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
      isImg = props.fileType.some(type => file.type.indexOf(type) > -1 || fileExtension.indexOf(type) > -1);
    }
    if (!isImg) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
    if (props.fileSize) {
      const isLt = file.size / 1024 / 1024 < props.fileSize;
      if (!isLt) {
        proxy.$modal.msgError(`上传excel大小不能超过 ${props.fileSize} MB!`);
        return false;
      }
    }
    proxy.$modal.loading("正在上传excel，请稍候...");
    return true;
  };

  // 数据导入相关功能
  const handleImport = () => {
    excelopen.value = true;
  };

  // 提交上传
  const submitUpload = () => {
    uploadRef.value.submit();
  };

  return {
    excelopen,
    uploadRef,
    handleUploadSuccess,
    handleUploadError,
    handleBeforeUpload,
    handleImport,
    submitUpload
  };
}